package com.achievo.reportserver.mq;

import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import com.achievo.reportserver.config.ConfigFactory;
import com.achievo.reportserver.config.ReportDef;
import com.achievo.reportserver.config.ReportParam;


/**
 * 
 * Report Server
 * write at Jan 21, 2010
 * @author <a href="mailto:chinaoryx@gmail.com">Hyman.Zhang (Zhang Haipeng)</a>
 * @version 1.0
 * 
 *
 */
public class EmaiMessageListener implements MessageListener {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(EmaiMessageListener.class);

	public void onMessage(Message message) {
		if (logger.isDebugEnabled()) {
			logger.debug("onMessage(Message=" + message + ") - start");
		}

		try {
			if (message instanceof TextMessage) {
				TextMessage txtMsg = (TextMessage) message;
				String msg = txtMsg.getText();

				String json = txtMsg.getStringProperty("json");
				JSONObject jsonObj = null;
				jsonObj = JSONObject.fromObject(json);

				Object obj = JSONObject.toBean(jsonObj);

				Map<String, Class> classMap = new Hashtable<String, Class>();
				classMap.put("paramList", ReportParam.class);
				classMap.put("mailList", String.class);

				ReportDef reportDef = (ReportDef) JSONObject.toBean(jsonObj, ReportDef.class, classMap);
				String outFileName = reportDef.getOutFileName();
				String outFileServerRootpath = reportDef.getOutFileServerPathRoot();
				String downloadUrl = outFileServerRootpath + outFileName;

				XMLSerializer xmlSerializer = new XMLSerializer();
				String xml = xmlSerializer.write(jsonObj);

				Configuration serverConfig = ConfigFactory.getServerConfig();
				String host = serverConfig.getString("mail.smtpHost");
				String username = serverConfig.getString("mail.username");
				String password = serverConfig.getString("mail.password");

				HtmlEmail email = new HtmlEmail();
				email.setHostName(host);
				email.setAuthentication(username, password);

				StringBuffer mailBody = new StringBuffer();

				mailBody.append("Hi,<br>");
				mailBody.append("reportId:\t");
				mailBody.append(reportDef.getReportId());
				mailBody.append("<br>");
				List<ReportParam> paramList = reportDef.getParamList();
				if (paramList != null) {
					for (ReportParam reportParam : paramList) {
						mailBody.append("param[");
						mailBody.append(reportParam.getParamName());
						mailBody.append("]:\t");
						mailBody.append(reportParam.getParamValue());

						mailBody.append("<br>");
					}
				}
				
				
				if ("OK".equals(msg)) {
					mailBody.append("Please download form here:<br>");
					mailBody.append(downloadUrl);
				} else {
					mailBody.append("error happens:<br>");
					mailBody.append("<pre>");
					mailBody.append(txtMsg.getStringProperty("desc"));
					mailBody.append("</pre>");
				}
				

				Collection<String> mailColl = reportDef.getMailList();
				StringBuffer mailAddresses = new StringBuffer();
				if (mailColl != null) {
					for (String emailAddr : mailColl) {
						email.addTo(emailAddr, "");
					}
				}
				
				email.setFrom("hyman.zhang@achievo.com", "Hyman Zhang");
				
				email.setHtmlMsg(mailBody.toString());
				email.setSubject("report result");

				// set the alternative message
				email.setTextMsg("Your email client does not support HTML messages");

				// send the email
				email.send();

			}
		} catch (Exception e) {
			logger.error("onMessage(Message) - exception ignored", e);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("onMessage(Message=" + message + ") - end");
		}
	}

}
